package com.lanhai.agv.listener;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

import com.lanhai.agv.queue.AgvEventQueue;
import com.lanhai.agv.queue.AgvEventUnit;

/**
 *  小车的消息获取
 * @author virus408
 *
 */
public class AgvListener {

	private boolean running;
	private Thread th;
	
	public void Start(int port) {
		running=true;
		th=new Thread() { 
			@Override
			public void run() {
				try{ 
					DatagramSocket	ds = new DatagramSocket(port);
					while(running){
						byte buf[] = new byte[20];
						DatagramPacket dp = new DatagramPacket(buf, buf.length);
						ds.receive(dp);
					 
						AgvEventUnit unit=new AgvEventUnit();
						unit.setData(buf);
						unit.setIp(dp.getAddress().getHostAddress()); 
						AgvEventQueue.Push(unit);
					}	
					ds.close();
				}catch(Exception e){
					e.printStackTrace();
				}	
			}
			
		};
		th.start();
	}
	 
	
	public void Stop() {
		running=false;
		try {
			th.interrupt();
			th=null; 
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
}
